package com.hk.freebbs;

import java.io.IOException;
import java.util.ArrayList;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import javax.servlet.http.HttpSession;

import com.hk.action.Action;
import com.hk.action.ActionForward;
import com.hk.service.BBSService;
import com.hk.service.LoginService;
import com.hk.dtos.AdminDto;
import com.hk.dtos.BBSDto;
import com.hk.dtos.UserDto;
import com.hk.file.FileManager;
import com.jungbo.file.dto.FileDto;


public class WriteGoAction implements Action{
	public ActionForward execute(HttpServletRequest request,
			HttpServletResponse response) {
		ActionForward forword=new ActionForward();
	
	BBSService manager=BBSService.getInstance();
	LoginService lmanager=LoginService.getInstance();
	FileManager fmanager=new FileManager();
	BBSDto dto = new BBSDto();
	FileDto fdto = new FileDto();
	String id = request.getParameter("id");
    String tcontent = request.getParameter("content");
    String title = request.getParameter("title");
    String pwd = request.getParameter("pwd");
    String tfcount = request.getParameter("fcount");
    
  
    
    int fcount=0;
    if(tfcount!=null || tfcount!="0"){
    fcount = Integer.parseInt(tfcount);
  
    }
    
    
    String bcontent = tcontent.replace("\n", "<br>");
    String content = bcontent.replace(" ", "&nbsp;");
    
//    String fseq = request.getParameter("fseq");
//    int fileseq = Integer.parseInt(fseq);
    int fseq = 0;
    
	ArrayList<BBSDto> result = manager.maxSeq("FREEBBS");
	int seq=0;
	if(result!=null){
	for(int i=0; i<result.size(); i++){
    BBSDto s =result.get(i);
    
    if(seq<s.getSeq())
    	seq=s.getSeq();
	}
	}
	ArrayList<FileDto> fresult = fmanager.maxfseq();
	
	for(int i=0; i<fresult.size(); i++){
    FileDto fs =fresult.get(i);
    
    if(fseq<fs.getFileseq())
    	fseq=fs.getFileseq();
	}
	seq = seq + 1;
    
	dto.setBbsname("FREEBBS");
    dto.setId(id);
    dto.setContent(content);
    dto.setTitle(title);
    if(!pwd.equals(null)){
    	dto.setPwd(pwd);
    }
    manager.insBoard(dto);
    
    if(tfcount!=null){
    for(int i=0; i<fcount; i++){
    fdto.setSeq(seq);
    fdto.setFileseq(fseq-i);
    fmanager.fseqUpdate(fdto);
    }
    }
    fmanager.addmod();
		
    lmanager.pointup(id);
    UserDto t = new UserDto();
    
    t=lmanager.login(id);
    if(t.getScore()%10==0){
    	lmanager.autup(id);	
    }
    
   
	forword.setUrl("start");
	forword.setRedirect(false);

	return forword;
}
	
}
